package com.blustreaksw.cyclecoach.userManagment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;

import com.blustreaksw.cyclecoach.MainActivity;
import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.UserManagementActivity;
import com.blustreaksw.cyclecoach.UserProfileActivity;
import com.blustreaksw.cyclecoach.data.UserProfile;
import com.blustreaksw.cyclecoach.export.DropboxConnector;
import com.blustreaksw.cyclecoach.util.NotificationDialogFragment;

/***********************************************************************
 * Display creation and UI logic for configuration of cloud data
 * storage providers. Currently supports the following:
 * <BR>
 * <BR>Dropbox
 * 
 * @author Tomas Rivera
 *
 ***********************************************************************/
public class Fragment_Wizard_DataExport extends Fragment {
	
	TableRow mDropboxButton;
	TextView mDropboxConfiguredTextView;
	
	DropboxConnector mDropboxConnector;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		setRetainInstance(true);
		mDropboxConnector = DropboxConnector.getInstance(getActivity());
		
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_wizard_configure_data_export,
				container, false);
		
		getActivity().setTitle("Export Settings");
		
		// Show Dropbox status
		mDropboxConfiguredTextView = (TextView) v.findViewById(R.id.exportSettings_dropboxConfigured);
		if(mDropboxConnector.isLoggedIn()) {
			mDropboxConfiguredTextView.setText("Authenticated");
		} else {
			mDropboxConfiguredTextView.setText("Not Configured");
		}
		
		
		// Configure Dropbox controls
		mDropboxButton = (TableRow) v.findViewById(R.id.exportSettings_dropboxButton);
		mDropboxButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mDropboxConnector.isLoggedIn()) {
					// Ask if we would like to log out.
					// TODO
					mDropboxConnector.logOut(getActivity());
					mDropboxConfiguredTextView.setText("Not Configured");
				} else if(isNetworkAvailable()){
					mDropboxConnector.connectToDropbox(getActivity());
				}
			}
		});
		
		
		
		return v;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(mDropboxConnector != null && mDropboxConnector.authenticationPending()) {
			// Make calls to complete authentication just in case we're returning to
			// this fragment after attempting to connect to a cloud storage service.
			mDropboxConnector.completeAuthentication(getActivity());
			
			if(mDropboxConnector.isLoggedIn()) {
				mDropboxConfiguredTextView.setText("Authenticated");
			} else {
				mDropboxConfiguredTextView.setText("Not Configured");
			}
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		mDropboxConnector.clearKeys(getActivity());
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		if(((UserProfileActivity)getActivity()).isWizardActivity()) {
			// Show only cancel, previous and save buttons.
			menu.findItem(R.id.action_createUserWizard_cancelButton).setVisible(true);
			menu.findItem(R.id.action_createUserWizard_prevButton).setVisible(true);
			menu.findItem(R.id.action_createUserWizard_saveButton).setVisible(true);
			
			
			// Hidden options
			menu.findItem(R.id.action_createUserWizard_newUser).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_nextButton).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_restartDeviceScan).setVisible(false);
			menu.findItem(R.id.scanning_indicator)
	        .setActionView(R.layout.progress_indicator).setVisible(false);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {

    		case R.id.action_createUserWizard_cancelButton:
    			getActivity().getSupportFragmentManager().popBackStack();
    			getActivity().getSupportFragmentManager().popBackStack();
    			getActivity().getSupportFragmentManager().popBackStackImmediate();
    			return true;
    			
    		case R.id.action_createUserWizard_prevButton:
    			// Return to the Create_User_2 activity
    			getActivity().getSupportFragmentManager().popBackStackImmediate();
    			return true;
    			
    		
    		case R.id.action_createUserWizard_saveButton:
    			
    			saveCloudServiceKeys();
    			
    			// Verify the last page of data and then save
    			getUserProfileFromActivity().insertNewUserFromCurrentProfile(getActivity());
    			
    			// Debug UserProfile Db insert
    			getUserProfileFromActivity().dumpUserInfoToLogCat(getUserProfileFromActivity().getId());
    			
    			
    			// Go to the main menu screen.
    			Intent i = new Intent(getActivity(), MainActivity.class);
    			i.putExtra(MainActivity.EXTRA_USER_ID, getUserProfileFromActivity().getId());
    			startActivity(i);
    			getActivity().finish();
    			return true;
    		
    		case R.id.action_createUserWizard_newUser:
    		case R.id.action_createUserWizard_restartDeviceScan:
    		case R.id.action_createUserWizard_nextButton:
    		default:
    			return super.onOptionsItemSelected(item); 
    	}
	}
	
	private void saveCloudServiceKeys() {
		String dropboxKeys[] = mDropboxConnector.getKeys(getActivity());
		
		if(dropboxKeys != null) {
			getUserProfileFromActivity().setKey_dropbox(dropboxKeys[0]);
			getUserProfileFromActivity().setSecret_dropbox(dropboxKeys[1]);
			mDropboxConnector.clearKeys(getActivity());
		}
	}
	
	private boolean isNetworkAvailable() {
		ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
		if(netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
			return true;
		}
		
		final String message = new String("Network is currently unavailable. Please verify you currently have WiFi or Cellular data service available and try again.");

        new NotificationDialogFragment().configureDialog(new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// Do nothing
			}
		}, "Network error", message, getActivity())
		.onCreateDialog(null).show();
		
		return false;
	}
	
	private UserProfile getUserProfileFromActivity() { return ((UserProfileActivity)getActivity()).getUserProfile(); }
}
